package com.allwees.bs.c.module.user.req;

import com.allwees.bs.core.model.constant.CacheName;
import com.allwees.bs.core.modelbase.constant.ResultEnum;
import com.allwees.bs.core.modelbase.exception.BusinessException;
import com.allwees.bs.core.modelbase.req.Req;
import com.allwees.bs.core.modelbase.validate.ValidateItem;
import com.allwees.core.cache.RedisUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCrypt;

@Data
@EqualsAndHashCode(callSuper = true)
public class ChangeEmailReq extends Req {

    private ChangeEmailVerifyType verifyType;

    private String verifyCode;

    private String newEmail;

    private String password;

    @Override
    public ValidateItem[] getValidateItems() {
        return new ValidateItem[]{
                new ValidateItem(verifyType == null, "verify type can not be null"),
                new ValidateItem(verifyType.equals(ChangeEmailVerifyType.CODE) && StringUtils.isBlank(verifyCode), "verifyCode can not be blank"),
                new ValidateItem(verifyType.equals(ChangeEmailVerifyType.PWD) && StringUtils.isBlank(password), "password can not be blank"),
                new ValidateItem(StringUtils.isBlank(newEmail), "new email can not be blank"),
        };
    }

    public boolean isValidatePwd() {
        return ChangeEmailVerifyType.PWD.equals(verifyType);
    }

    public void validateCode(String userUuid) {
        String code = RedisUtil.hget(CacheName.USER_INIT_EMAIL_VERIFY_CODE, userUuid);
        if (StringUtils.isBlank(code)) {
            throw BusinessException.getInstance(ResultEnum.VERIFY_CODE_EXPIRED);
        }
        if (!verifyCode.equalsIgnoreCase(code)) {
            throw BusinessException.getInstance(ResultEnum.VERIFY_CODE_NOT_VALID);
        }
    }

    public void validatePwd(String originalPwd) {
        if (!BCrypt.checkpw(password, originalPwd)) {
            throw BusinessException.getInstance(ResultEnum.USERS_ORIGIN_PASSWORD_NOT_VALID);
        }
    }

    public enum ChangeEmailVerifyType {
        PWD,
        CODE
    }
}


